In [1]:
import pandas as pd
import geopandas as gpd
# from jupyterthemes import jtplot
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.io as pio
import basedosdados as bd
import sqlite3 as sqlite
In [2]:
pio.renderers.default='notebook'
In [3]:
dbpath = 'cities.db' 

# Create connection and load spatialite extension
con = sqlite.connect(dbpath)
con.enable_load_extension(True)
con.execute('SELECT load_extension("mod_spatialite")')

# SQL must wrap the geometry in hex(st_asbinary(...))
sql = "SELECT id, sigla_uf, name, Hex(ST_AsBinary(geometry)) as geom FROM cities;"
df = gpd.GeoDataFrame.from_postgis(sql, con, geom_col="geom")

Expectativa de vida

Passaremos ao segundo indicador, buscando determinar se há alguma correlação entre este fator e a mortalidade por Covid-19 nos municípios do Rio de Janeiro. Para isso, utilizamos o ADH, Atlas do Desenvolvimento Humano, criado pela ONU, e que tem dentre suas informações a expectativa de vida. O banco de dados utilizado para esta parte também pertence à Base dos Dados, e os obtemos a seguir, utilizando o censo do IBGE mais recente, de 2010:

In [4]:
life_exp = bd.read_sql(
    '''
    SELECT id_municipio AS id, expectativa_vida
    FROM  basedosdados.mundo_onu_adh.municipio
    WHERE ano = 2010
    ''',
    billing_project_id='adameplayground')
Downloading: 100%|██████████| 5565/5565 [00:00<00:00, 9955.32rows/s] 

Para isso, fazemos o merge a partir do id com o dataframe espacial, mantendo apenas os do estado do RJ, e fazendo as conversões necessárias.

In [5]:
cities_health = pd.merge(df, life_exp, how='inner', on='id')
rj_health = cities_health[cities_health['sigla_uf'] == 'RJ']
rj_health['id'] = rj_health['id'].astype(int)
rj_health.head()
Out[5]:
id sigla_uf name geom expectativa_vida
2350 3300100 RJ Angra dos Reis POLYGON ((-44.19557 -23.09831, -44.19445 -23.1... 75.75
2351 3300233 RJ Armação dos Búzios POLYGON ((-41.93436 -22.76580, -41.91900 -22.7... 74.44
2352 3300258 RJ Arraial do Cabo POLYGON ((-42.23767 -22.86367, -42.23403 -22.8... 73.31
2353 3300308 RJ Barra do Piraí POLYGON ((-43.97101 -22.32489, -43.96619 -22.3... 74.14
2354 3300456 RJ Belford Roxo POLYGON ((-43.36512 -22.68504, -43.35048 -22.6... 73.50

Agora podemos fazer o gráfico do estado novamente, analisando a expectativa de vida para cada município. Note que esse índice se parece mais com o que havíamos visto do IDH do que o de educação, o que pode nos indicar uma queda na correlação entre os fatores.

In [6]:
fig = px.choropleth(rj_health,
                   geojson = rj_health["geom"],
                   locations = rj_health.index,
                   color = "expectativa_vida",
                   hover_name = "name",
                   hover_data = ["expectativa_vida"],
                   labels = {
                       "expectativa_vida": "Expectativa de vida"
                   },
                   color_continuous_scale = "Burg",
                   #animation_frame = 'date',
)

fig.update_geos(
                projection=dict(
                    scale=55
                    ),
                center = dict(
                    lat=-22.208333,
                    lon=-42.896388
                    )
)

fig.update_layout(
    title_text = "ADH de 2010, por município do RJ",
    margin={"r":0,"t":50,"l":0,"b":50}
)

fig.show()

Ainda assim, realizaremos o mesmo processo anterior a partir dos dados de covid e da expectativa de vida.

In [7]:
covid = pd.read_csv('caso_full.csv.gz', compression='gzip')
filt = (covid['state']  == 'RJ') & (covid['place_type'] == 'city') & (covid['is_last']) 
uniq = covid[filt]['city'].isin(rj_health['name'])
rj_covid = covid[filt][uniq]
In [8]:
rj_covid['id'] = rj_covid['city_ibge_code'].astype(int)
rj_covid = rj_covid.copy()[['id', 'estimated_population', 'last_available_confirmed_per_100k_inhabitants', 'last_available_death_rate']]
health_covid_rj = pd.merge(rj_health, rj_covid, how='inner', on='id')
health_covid_rj.head()
Out[8]:
id sigla_uf name geom expectativa_vida estimated_population last_available_confirmed_per_100k_inhabitants last_available_death_rate
0 3300100 RJ Angra dos Reis POLYGON ((-44.19557 -23.09831, -44.19445 -23.1... 75.75 207044.0 8288.57634 0.0315
1 3300233 RJ Armação dos Búzios POLYGON ((-41.93436 -22.76580, -41.91900 -22.7... 74.44 34477.0 16480.55225 0.0128
2 3300258 RJ Arraial do Cabo POLYGON ((-42.23767 -22.86367, -42.23403 -22.8... 73.31 30593.0 3010.49260 0.0478
3 3300308 RJ Barra do Piraí POLYGON ((-43.97101 -22.32489, -43.96619 -22.3... 74.14 100764.0 7481.83875 0.0517
4 3300456 RJ Belford Roxo POLYGON ((-43.36512 -22.68504, -43.35048 -22.6... 73.50 513118.0 4634.02180 0.0386

Certamente é necessário confirmar a desconfiança que temos de que a correlação será baixa, então faremos a análise a seguir:

In [9]:
fig = px.scatter(health_covid_rj, x="last_available_death_rate", y="expectativa_vida", hover_data=['name'], trendline="ols",
 color_discrete_sequence=['#FF84DD'],trendline_color_override="orange",
title="Gráfico de dispersão entre taxa de mortalidade e ADH",
labels={"last_available_death_rate": "Taxa de mortalidade",
        "name": "Município",
        "expectativa_vida":"Expectativa de vida"})
fig.show()

Observe que, de fato, os pontos não apresentaram qualquer linearidade ou mesmo indicação de tendência, espalhando-se de forma apararentemente desordenada. A linha de tendência traçada tem o $R^2$ baixíssimo, e mesmo visualmente não parece ser acompanhada pelos pontos do gráfico. Assim, constatamos que o segundo indicador não tem correlação clara com a taxa de mortes por Covid-19 no estado, e passamos ao último indicador para podermos responder à pergunta original.

In [11]:
!jupyter nbconvert health_analysis.ipynb --to html --template classic
This application is used to convert notebook files (*.ipynb)
        to various other formats.

        WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.

Options
=======
The options below are convenience aliases to configurable class-options,
as listed in the "Equivalent to" description-line of the aliases.
To see all configurable class-options for some <cmd>, use:
    <cmd> --help-all

--debug
    set log level to logging.DEBUG (maximize logging output)
    Equivalent to: [--Application.log_level=10]
--show-config
    Show the application's configuration (human-readable format)
    Equivalent to: [--Application.show_config=True]
--show-config-json
    Show the application's configuration (json format)
    Equivalent to: [--Application.show_config_json=True]
--generate-config
    generate default config file
    Equivalent to: [--JupyterApp.generate_config=True]
-y
    Answer yes to any questions instead of prompting.
    Equivalent to: [--JupyterApp.answer_yes=True]
--execute
    Execute the notebook prior to export.
    Equivalent to: [--ExecutePreprocessor.enabled=True]
--allow-errors
    Continue notebook execution even if one of the cells throws an error and include the error message in the cell output (the default behaviour is to abort conversion). This flag is only relevant if '--execute' was specified, too.
    Equivalent to: [--ExecutePreprocessor.allow_errors=True]
--stdin
    read a single notebook file from stdin. Write the resulting notebook with default basename 'notebook.*'
    Equivalent to: [--NbConvertApp.from_stdin=True]
--stdout
    Write notebook output to stdout instead of files.
    Equivalent to: [--NbConvertApp.writer_class=StdoutWriter]
--inplace
    Run nbconvert in place, overwriting the existing notebook (only 
            relevant when converting to notebook format)
    Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory=]
--clear-output
    Clear output of current file and save in place, 
            overwriting the existing notebook.
    Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory= --ClearOutputPreprocessor.enabled=True]
--no-prompt
    Exclude input and output prompts from converted document.
    Equivalent to: [--TemplateExporter.exclude_input_prompt=True --TemplateExporter.exclude_output_prompt=True]
--no-input
    Exclude input cells and output prompts from converted document. 
            This mode is ideal for generating code-free reports.
    Equivalent to: [--TemplateExporter.exclude_output_prompt=True --TemplateExporter.exclude_input=True --TemplateExporter.exclude_input_prompt=True]
--allow-chromium-download
    Whether to allow downloading chromium if no suitable version is found on the system.
    Equivalent to: [--WebPDFExporter.allow_chromium_download=True]
--disable-chromium-sandbox
    Disable chromium security sandbox when converting to PDF..
    Equivalent to: [--WebPDFExporter.disable_sandbox=True]
--show-input
    Shows code input. This is flag is only useful for dejavu users.
    Equivalent to: [--TemplateExporter.exclude_input=False]
--log-level=<Enum>
    Set the log level by value or name.
    Choices: any of [0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL']
    Default: 30
    Equivalent to: [--Application.log_level]
--config=<Unicode>
    Full path of a config file.
    Default: ''
    Equivalent to: [--JupyterApp.config_file]
--to=<Unicode>
    The export format to be used, either one of the built-in formats
            ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'slides', 'webpdf']
            or a dotted object name that represents the import path for an
            ``Exporter`` class
    Default: ''
    Equivalent to: [--NbConvertApp.export_format]
--template=<Unicode>
    Name of the template to use
    Default: ''
    Equivalent to: [--TemplateExporter.template_name]
--template-file=<Unicode>
    Name of the template file to use
    Default: None
    Equivalent to: [--TemplateExporter.template_file]
--writer=<DottedObjectName>
    Writer class used to write the 
                                        results of the conversion
    Default: 'FilesWriter'
    Equivalent to: [--NbConvertApp.writer_class]
--post=<DottedOrNone>
    PostProcessor class used to write the
                                        results of the conversion
    Default: ''
    Equivalent to: [--NbConvertApp.postprocessor_class]
--output=<Unicode>
    overwrite base name use for output files.
                can only be used when converting one notebook at a time.
    Default: ''
    Equivalent to: [--NbConvertApp.output_base]
--output-dir=<Unicode>
    Directory to write output(s) to. Defaults
                                  to output to the directory of each notebook. To recover
                                  previous default behaviour (outputting to the current 
                                  working directory) use . as the flag value.
    Default: ''
    Equivalent to: [--FilesWriter.build_directory]
--reveal-prefix=<Unicode>
    The URL prefix for reveal.js (version 3.x).
            This defaults to the reveal CDN, but can be any url pointing to a copy 
            of reveal.js. 
            For speaker notes to work, this must be a relative path to a local 
            copy of reveal.js: e.g., "reveal.js".
            If a relative path is given, it must be a subdirectory of the
            current directory (from which the server is run).
            See the usage documentation
            (https://nbconvert.readthedocs.io/en/latest/usage.html#reveal-js-html-slideshow)
            for more details.
    Default: ''
    Equivalent to: [--SlidesExporter.reveal_url_prefix]
--nbformat=<Enum>
    The nbformat version to write.
            Use this to downgrade notebooks.
    Choices: any of [1, 2, 3, 4]
    Default: 4
    Equivalent to: [--NotebookExporter.nbformat_version]

Examples
--------

    The simplest way to use nbconvert is

            > jupyter nbconvert mynotebook.ipynb --to html

            Options include ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'slides', 'webpdf'].

            > jupyter nbconvert --to latex mynotebook.ipynb

            Both HTML and LaTeX support multiple output templates. LaTeX includes
            'base', 'article' and 'report'.  HTML includes 'basic', 'lab' and 
            'classic'. You can specify the flavor of the format used.

            > jupyter nbconvert --to html --template lab mynotebook.ipynb

            You can also pipe the output to stdout, rather than a file

            > jupyter nbconvert mynotebook.ipynb --stdout

            PDF is generated via latex

            > jupyter nbconvert mynotebook.ipynb --to pdf

            You can get (and serve) a Reveal.js-powered slideshow

            > jupyter nbconvert myslides.ipynb --to slides --post serve

            Multiple notebooks can be given at the command line in a couple of 
            different ways:

            > jupyter nbconvert notebook*.ipynb
            > jupyter nbconvert notebook1.ipynb notebook2.ipynb

            or you can specify the notebooks list in a config file, containing::

                c.NbConvertApp.notebooks = ["my_notebook.ipynb"]

            > jupyter nbconvert --config mycfg.py

To see all available configurables, use `--help-all`.

[NbConvertApp] WARNING | pattern 'health_analysis.ipynb' matched no files